import { ILoginUserForm } from "@/apis/types"
import { loginApi } from "@/apis/web/Login"
import global from "@/global"
import { useCookie } from "@/hooks/useCookie"
import { useCrypto } from "@/hooks/useCrypto"
import { useReset } from "@/hooks/useReset"
import router from "@/router"
import store, { RootState } from "@/store"
import { ElMessage } from "element-plus"
import { Module } from "vuex"
import { IPromissionActions, IPromissionGetter, IPromissionMutations, IPromissionState } from "./types"

const state: IPromissionState = {
    token: "",
    role: ""
}

const actions: IPromissionActions = {
    onLogin: ({ commit }, form: ILoginUserForm) => {
        // if (form.username?.length < 10) {
        //     useElMessage().info('账号长度必须大于等于十！')
        // } else if (!isStrNumber(form.username)) {
        //     useElMessage().info('账号必须为数字！')
        // } else if (form.password?.length < 6) {
        //     useElMessage().info('密码长度必须大于等于六！')
        // } else {
        //     commit('_onLogin', form);
        //     form = { username: '', password: '' }
        // }
        commit("_onLogin", form)
    },
    // 是否有权限
    hasPermission: ({ state }, role) => state.role === role,
    // 权限判断
    hasPermissionJudge: ({ state }, role: string | string[]) => state.role === role || role.includes(state.role)
}

const mutations: IPromissionMutations = {
    _onLogin: async (state, form: ILoginUserForm) => {
        const { encrypt } = useCrypto()
        const encryptedForm = {
            username: encrypt(form.username),
            password: encrypt(form.password)
        }

        const { token, role, user } = await loginApi(encryptedForm)
        useCookie().setCookie(global.cookiesTokenName, token)
        state.token = token
        state.role = role
        store.commit('user/_setUser', user)
        // 动态加载路由
    },
    // 退出登录
    _onLogout: state => {
        const { resetAll } = useReset()
        resetAll()
        router.push("/")
        ElMessage({
            message: '退出成功',
            type: 'success',
        });
    },
    // 重置PermissionStoreState
    _resetPermissionStoreState: state => {
        state.token = ""
        state.role = ""
    }
}
const getters: IPromissionGetter = {
    getToken: state => {
        return state.token
    },
    getRole: state => {
        return state.role
    }
}

export const permission: Module<IPromissionState, RootState> = {
    namespaced: true,
    state,
    actions,
    mutations,
    getters
}
